package com.zking.forward.product;

import com.zking.dao.HistoryDao;
import com.zking.dao.ProductDao;
import com.zking.entity.HistoryItem;
import com.zking.entity.Product;
import com.zking.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;

@WebServlet("/productSelectById")
public class ProductSelectById extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理请求的编码，解决中文乱码
        request.setCharacterEncoding("utf-8");
        //处理响应的编码 ，解决中文乱码
        response.setContentType("text/html;charset=utf-8");

        System.out.println("ProductSelectById===进来");

        int id = Integer.parseInt(request.getParameter("id"));
        Product product = ProductDao.selectProductById(id);

        // 增加浏览历史
        User user  =(User)request.getSession().getAttribute("user");
        if(user!=null && product!=null){
            HistoryItem historyItem = new HistoryItem(0, user.getEu_user_id(),
                    product.getEp_id(), product.getEp_name(), product.getEp_image_bytes());
            HistoryDao.addHistoryItem(historyItem);
        }

        request.setAttribute("product", product);
        if(product!=null)
        {
            if(product.getEp_image_bytes()!=null){
                request.setAttribute("image", Base64.getEncoder().encodeToString(product.getEp_image_bytes()));
            }
        }
        request.getRequestDispatcher("product-view.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
